package com.atguigu.day02;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class Resource{
    private int num=0;

//    public synchronized void increment() throws InterruptedException {
//        while (num!=0){
//            this.wait();
//        }
//        System.out.println(Thread.currentThread().getName()+"="+(++num));
//        this.notifyAll();
//    }
//
//    public synchronized void decrement() throws InterruptedException {
//       while (num!=1){
//            this.wait();
//        }
//        System.out.println(Thread.currentThread().getName()+"="+(--num));
//        this.notifyAll();
//    }

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public  void increment(){


        lock.lock();
        try{
            while (num !=0){
                condition.await();
            }
            System.out.println(Thread.currentThread().getName()+"="+(++num));
            condition.signalAll();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }


    public  void decrement(){
    lock.lock();
    try{
        while (num!=1){
            condition.await();
        }
        System.out.println(Thread.currentThread().getName()+"="+(--num));
        condition.signalAll();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } finally {
        lock.unlock();
    }


    }
}






public class ProducerAndConsumer {
    public static void main(String[] args) {
        Resource resource = new Resource();

        new Thread(() -> {
            for (int i = 0; i <20 ; i++) {
                    resource.increment();
            }
        },"线程1").start();


        new Thread(() -> {
            for (int i = 0; i <20 ; i++) {
                    resource.decrement();
            }
        },"线程2").start();

        new Thread(() -> {
            for (int i = 0; i <20 ; i++) {

                    resource.increment();

            }
        },"线程3").start();

        new Thread(() -> {
            for (int i = 0; i <20 ; i++) {
                    resource.decrement();
            }
        },"线程4").start();

    }
}
